#! /usr/bin/env python
# -*- coding: utf-8 -*-

from django import forms
from web.form.bootstrap import BootStrap
from web import models
from django.core.exceptions import ValidationError


class IssuesModelForm(BootStrap, forms.ModelForm):

    class Meta:
        model = models.Issues
        exclude = ['project', 'creator', 'create_datetime', 'latest_update_datetime']
        # 修改为bootstrap-select

        widgets = {
            "assign": forms.Select(attrs={'class': "selectpicker", "data-live-search": "true"}),
            "module": forms.Select(attrs={'class': "selectpicker", "data-live-search": "true"}),
            "issue_type": forms.Select(attrs={'class': "selectpicker", "data-live-search": "true"}),
            "parent": forms.Select(attrs={'class': "selectpicker", "data-live-search": "true"}),
            "attention": forms.SelectMultiple(attrs={'class': "selectpicker",
                                                     "data-live-search": "true",
                                                     "data-actions-box": "true",
                                                     }),

        }

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 数据处理初始化
        # 1. 获取当前项目是所有问题类型 values_list -> [(1, 'xx'), (2, 'xx')]
        self.fields['issue_type'].choices = models.IssuesType.objects.filter(
            project=request.tracer.project).values_list('id', 'title')

        # 2. 模块
        module_list = [('', '没有选中任何项')]
        module_obj_list = models.Module.objects.filter(
            project=request.tracer.project).values_list('id', 'title')
        module_list.extend(module_obj_list)
        self.fields['module'].choices = module_list

        # 3. 指派者关注者
        # 找到当前项目的参与者和创建者
        total_user_list = [(request.tracer.project.creator.id, request.tracer.project.creator.username), ]

        project_user_list = models.ProjectUser.objects.filter(
            project=request.tracer.project).values_list('user_id', 'user__username')
        total_user_list.extend(project_user_list)
        self.fields['assign'].choices = [('', '没有选中任何项')] + total_user_list
        self.fields['attention'].choices = total_user_list

        # 4. 父问题
        # 当前项目已创建的所有问题
        parent_list = [('', '没有选中任何项')]
        parent_obj_list = models.Issues.objects.filter(project=request.tracer.project).values_list('id', 'subject')
        parent_list.extend(parent_obj_list)
        self.fields['parent'].choices = parent_list


class IssuesReplyModelForm(forms.ModelForm):

    class Meta:
        model = models.IssuseReply
        fields = ['content', 'reply']

